<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="图书名称" prop="bookName">
        <el-input
          v-model="queryParams.bookName"
          placeholder="请输入图书名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="图书编码" prop="bookNo">
        <el-input
          v-model="queryParams.bookNo"
          placeholder="请输入图书编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:book:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:book:edit']"
          >修改</el-button
        >
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-s-promotion"
          size="mini"
          @click="handleBorrow"
          v-hasPermi="['system:book:export']"
          >图书借阅</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-s-ticket"
          size="mini"
          @click="handelReturnBooks"
          v-hasPermi="['system:book:export']"
          >图书归还</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-time"
          size="mini"
          @click="handelRenewalBooks"
          v-hasPermi="['system:book:export']"
          >图书续借</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="bookList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="图书编码" align="center" prop="bookNo" />
      <el-table-column label="图书名称" align="center" prop="bookName" />
      <el-table-column label="图书封面" align="center" prop="bookCoverPhoto">
        <template slot-scope="scope">
          　　　　<img
            :src="scope.row.bookCoverPhoto"
            width="60"
            height="60"
            class="head_pic"
          />
          　　</template
        >
      </el-table-column>
      <el-table-column label="作者" align="center" prop="author" />
      <el-table-column prop="bookStatus" label="图书状态" width="80">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.library_book_status"
            :value="scope.row.bookStatus"
          />
        </template>
      </el-table-column>
      <el-table-column label="图书类型" align="center" prop="bookType" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:book:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:book:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改图书馆图书对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="图书编码" prop="bookNo">
          <el-input v-model="form.bookNo" placeholder="请输入图书编码" />
        </el-form-item>
        <el-form-item label="图书名称" prop="bookName">
          <el-input v-model="form.bookName" placeholder="请输入图书名称" />
        </el-form-item>
        <el-form-item label="图书分类">
          <el-select v-model="form.bookType" placeholder="请选择分类">
            <el-option
              v-for="type in bookTypes"
              :key="type.id"
              :label="type.name"
              :value="type.no"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="书柜位置" prop="bookColumn">
          <el-input v-model="form.bookColumn" placeholder="请输入书柜位置" />
        </el-form-item>
        <el-form-item label="书柜层数" prop="bookLayer">
          <el-input v-model="form.bookLayer" placeholder="请输入书柜层数" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 图书借阅对话框 -->
    <el-dialog
      title="图书借阅"
      :visible.sync="borrow"
      width="700px"
      append-to-body
    >
      <el-form
        ref="form"
        :model="borrowForm"
        :rules="rules"
        label-width="180px"
      >
        <el-form-item label="会员编码(手机号)" prop="membersNo">
          <el-input
            v-model="borrowForm.membersNo"
            placeholder="请输入会员编码或手机号"
            @blur="searchMemberByMemberNoOrPhone"
          />
        </el-form-item>
        <el-form-item label="会员名称" prop="membersName">
          <el-input
            v-model="borrowForm.membersName"
            placeholder="请输入图书名称"
          />
        </el-form-item>
        <el-form-item label="图书编号">
          <el-input
            v-model="borrowForm.bookNo"
            placeholder="请输入图书编码"
            @blur="searchBooksByBookNo"
          />
        </el-form-item>
        <el-form-item label="图书名称">
          <el-input v-model="borrowForm.bookName" />
        </el-form-item>
      </el-form>
      <el-table :data="borrowForm.books" style="width: 100%">
        <el-table-column prop="bookNo" label="图书编码"> </el-table-column>
        <el-table-column prop="bookName" label="图书名称"> </el-table-column>
        <el-table-column prop="bookStatus" label="图书状态">
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.library_book_status"
              :value="scope.row.bookStatus"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="deleteBorrowBook(scope.row)"
              >删除</el-button
            ></template
          >
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="priary" @click="addsBorrowBook">确 定</el-button>
        <el-button @click="borrowCancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 图书归还对话框 -->
    <el-dialog
      title="图书归还"
      :visible.sync="returnBooks"
      width="800px"
      append-to-body
    >
      <el-form
        ref="form"
        :model="borrowForm"
        :rules="rules"
        label-width="180px"
      >
        <el-form-item label="会员编码(手机号)" prop="membersNo">
          <el-input
            v-model="borrowForm.membersNo"
            placeholder="请输入会员编码或手机号"
            @blur="selectReturnBooksByMembers"
          />
        </el-form-item>
        <el-form-item label="会员名称" prop="membersName">
          <el-input v-model="borrowForm.membersName" />
        </el-form-item>
      </el-form>
      <el-table :data="borrowForm.books" style="width: 100%">
        <el-table-column prop="bookNo" label="图书编码" width="80">
        </el-table-column>
        <el-table-column prop="bookName" label="图书名称"> </el-table-column>
        <el-table-column prop="borrowTime" label="借阅日期">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.borrowTime) }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="borrowDay" label="借阅天数">
          <template slot-scope="scope">
            <span>{{ difference(scope.row.borrowTime, new Date()) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="bookStatus" label="图书状态" width="100">
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.library_book_status"
              :value="scope.row.bookStatus"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="deleteBorrowBook(scope.row)"
              >删除</el-button
            ></template
          >
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="priary" @click="addreturnBooks">确 定</el-button>
        <el-button @click="returnBooksCancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 图书续期对话框 -->
    <el-dialog
      title="图书续期"
      :visible.sync="renewalBooks"
      width="800px"
      append-to-body
    >
      <el-form
        ref="form"
        :model="borrowForm"
        :rules="rules"
        label-width="180px"
      >
        <el-form-item label="会员编码(手机号)" prop="membersNo">
          <el-input
            v-model="borrowForm.membersNo"
            placeholder="请输入会员编码或手机号"
            @blur="selectReturnBooksByMembers"
          />
        </el-form-item>
        <el-form-item label="会员名称" prop="membersName">
          <el-input v-model="borrowForm.membersName" />
        </el-form-item>
      </el-form>
      <el-table :data="borrowForm.books" style="width: 100%">
        <el-table-column prop="bookNo" label="图书编码" width="80">
        </el-table-column>
        <el-table-column prop="bookName" label="图书名称"> </el-table-column>
        <el-table-column prop="borrowTime" label="借阅日期">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.borrowTime) }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="borrowDay" label="借阅天数">
          <template slot-scope="scope">
            <span>{{ difference(scope.row.borrowTime, new Date()) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="bookStatus" label="图书状态" width="100">
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.library_book_status"
              :value="scope.row.bookStatus"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="deleteBorrowBook(scope.row)"
              >删除</el-button
            ></template
          >
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="priary" @click="addRenewalBooks">确 定</el-button>
        <el-button @click="renewalBooksCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listBook,
  getBook,
  delBook,
  addBook,
  updateBook,
  getSelectBookType,
  searchBooks,
  adds,
  selectReturnBooksByMembers,
  returnBooks,
  continueBooks,
} from "@/api/library/book";
import { searchMember } from "@/api/library/members";

export default {
  name: "Book",
  dicts: ["library_book_status"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 图书馆图书表格数据
      bookList: [],

      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //图书借阅弹出层
      borrow: false,
      //图书归还弹出层
      returnBooks: false,
      //图书续期
      renewalBooks: false,
      //图书分类
      bookTypes: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        bookName: null,
        bookNo: null,
        bookStatus: null,
        bookType: null,
      },
      // 表单参数
      form: {},
      //图书借阅参数
      borrowForm: {
        membersNo: null,
        membersId: null,
        membersName: null,
        membersDepositType: null,
        membersDeposit: null,
        books: [],
        bookIds: [],
      },
      // 表单校验
      rules: {},
    };
  },
  created() {
    this.getList();
    this.getSelectBookType();
  },
  methods: {
    /** 查询图书馆图书列表 */
    getList() {
      this.loading = true;
      listBook(this.queryParams).then((response) => {
        this.bookList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    //图书借阅取消按钮
    borrowCancel() {
      this.borrow = false;
      this.borrowForm = {
        membersNo: null,
        membersId: null,
        membersName: null,
        membersDepositType: null,
        membersDeposit: null,
        books: [],
        bookIds: [],
      };
      this.getList();
    },
    /**图书续期 */
    renewalBooksCancel() {
      this.renewalBooks = false;
      this.borrowForm = {
        membersNo: null,
        membersId: null,
        membersName: null,
        membersDepositType: null,
        membersDeposit: null,
        books: [],
        bookIds: [],
      };
      this.getList();
    },
    //图书归还取消按钮
    returnBooksCancel() {
      this.returnBooks = false;
      this.borrowForm = {
        membersNo: null,
        membersId: null,
        membersName: null,
        membersDepositType: null,
        membersDeposit: null,
        books: [],
        bookIds: [],
      };
      this.getList();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        bookName: null,
        bookNo: null,
        bookStatus: "0",
        bookType: null,
        bookColumn: null,
        bookLayer: null,
        userId: null,
        createTime: null,
        updateTime: null,
        ext1: null,
        ext2: null,
        ext3: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /**根据手机号或用编号查询用户信息 */
    searchMemberByMemberNoOrPhone() {
      searchMember(this.borrowForm).then((res) => {
        if (res.code == 200) {
          this.borrowForm.membersName = res.data.membersName;
          this.borrowForm.membersId = res.data.id;
          this.borrowForm.membersDepositType = res.data.membersDepositType;
          this.borrowForm.membersDeposit = res.data.membersDeposit;
        }
      });
    },
    /**根据图书编号查询图书信息 */
    searchBooksByBookNo() {
      searchBooks(this.borrowForm).then((res) => {
        if (res.code == 200) {
          this.borrowForm.bookName = res.data.bookName;
          let book = {
            bookNo: res.data.bookNo,
            bookId: res.data.id,
            bookName: res.data.bookName,
            bookStatus: res.data.bookStatus,
          };
          let flag1 = this.borrowForm.books.findIndex(
            (item) => item.bookNo == book.bookNo
          );
          if (flag1 == -1) {
            this.borrowForm.books.push(book);
            this.borrowForm.bookIds.push(book.bookId);
          }
        }
      });
    },
    /**
     * 查询图书分类
     */
    getSelectBookType() {
      getSelectBookType().then((res) => {
        this.bookTypes = res.data;
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加图书馆图书";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getBook(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改图书馆图书";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateBook(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBook(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除图书馆图书编号为"' + ids + '"的数据项？')
        .then(function () {
          return delBook(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/book/export",
        {
          ...this.queryParams,
        },
        `book_${new Date().getTime()}.xlsx`
      );
    },
    /**图书借阅 */
    handleBorrow() {
      this.borrow = true;
    },
    /**图书归还 */
    handelReturnBooks() {
      this.returnBooks = true;
    },
    /**图书续期 */
    handelRenewalBooks() {
      this.renewalBooks = true;
    },
    /**删除借阅表格中数据项 */
    deleteBorrowBook(row) {
      const list = this.borrowForm.books.filter((item) => item !== row);
      const bookIds = this.borrowForm.bookIds.filter(
        (item) => item !== row.bookId
      );
      this.borrowForm.books = list;
      this.borrowForm.bookIds = bookIds;
    },
    /**批量图书借阅 */
    addsBorrowBook() {
      adds(this.borrowForm).then((res) => {
        if (res.code == 200) {
          this.borrowCancel();
        }
      });
    },
    /**根据用户查询已借阅信息 */
    selectReturnBooksByMembers() {
      searchMember(this.borrowForm).then((res) => {
        if (res.code == 200) {
          this.borrowForm.membersName = res.data.membersName;
          this.borrowForm.membersId = res.data.id;
          this.borrowForm.membersDepositType = res.data.membersDepositType;
          this.borrowForm.membersDeposit = res.data.membersDeposit;
          selectReturnBooksByMembers({ membersId: res.data.id }).then((res) => {
            console.log(res);
            if (res.code == 200) {
              res.data.forEach((element) => {
                let book = {
                  bookNo: element.boBook.bookNo,
                  bookId: element.bookId,
                  bookName: element.boBook.bookName,
                  bookStatus: element.boBook.bookStatus,
                  borrowTime: element.borrowTime,
                  bookStatus: 1,
                };
                let flag1 = this.borrowForm.books.findIndex(
                  (item) => item.bookNo == book.bookNo
                );
                if (flag1 == -1) {
                  this.borrowForm.books.push(book);
                  this.borrowForm.bookIds.push(book.bookId);
                }
              });
            }
          });
        }
      });
    },
    /**图书批量归还 */
    addreturnBooks() {
      returnBooks(this.borrowForm).then((res) => {
        if (res.code == 200) {
          this.returnBooksCancel();
        }
      });
    },
    /**图书续期 */
    addRenewalBooks() {
      continueBooks(this.borrowForm).then((res) => {
        if (res.code == 200) {
          this.renewalBooksCancel();
        }
      });
    },
  },
};
</script>
